--[[
游戏游戏一共有48张牌，1~9饼加上中发白，每种牌有4张，共计48张牌；每次发牌时随机抽取8张；每局从八张牌中随机成四份，分别发给庄家和闲家的中发白区域；
]]

local Rule = class("Rule")

function  Rule:ctor()
	--随机种子
	math.randomseed(os.time())
	--牌型说明，0x01~0x09(1~9饼)，0x10, 0x20, 0x30(白中发)
	self.card = {
		0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x20, 0x30
	}
	--要发的牌
	self.tbCard = {}
	self.cardPairs = 4	--每种牌有4张	
end

--洗牌
function Rule:shuffle()	
	self.tbCard = {}
	for i = 1, self.cardPairs do 
		for _, v in pairs(self.card) do 
			table.insert(self.tbCard, v)
		end
	end	
	table.mix(self.tbCard)
end

--取牌
function Rule:getCards()	
	local tb = {}
	for i=1, 8 do
		table.insert(tb, table.remove(self.tbCard))
	end
	return tb
end

--取本局剩余牌数
function Rule:getLeftCardCount()
	return #self.tbCard
end

--是否豹子(对子)
function Rule:isPair(tbCard)
	if #tbCard < 2 then 
		return false
	end
	return tbCard[1] == tbCard[2]
end

--是否天杠
function Rule:isTiangan(cards)
	if (cards[1] & 0x0f == 2 and cards[2] & 0x0f == 8) 
		or (cards[1] & 0x0f == 8 and cards[2] & 0x0f == 2) then
		return true
	end
	return false
end

--获取点数
function Rule:getPoint(tbCard)
	local point = ((tbCard[1] & 0x0f) + (tbCard[2] & 0x0f)) % 10
	return point
end

--比牌， bankCards大于playCards：1，小于-1
function Rule:compareCard(bankCards, playCards)
	--有天杠
	if self:isTiangan(bankCards) then
		return 1
	elseif self:isTiangan(playCards) then
		return -1	
	end

	--有对子
	if self:isPair(bankCards) and self:isPair(playCards) then
		if bankCards[1] >= playCards[1] then
			return 1
		else
			return -1
		end
	elseif self:isPair(bankCards) and not self:isPair(playCards) then
		return 1
	elseif not self:isPair(bankCards) and self:isPair(playCards) then
		return -1
	end

	--都是散牌
	if self:getPoint(bankCards) > self:getPoint(playCards) then
		return 1
	elseif self:getPoint(bankCards) < self:getPoint(playCards) then
		return -1
	else
		if bankCards[1] + bankCards[2] >= playCards[1] + playCards[2] then
			return 1
		else
			return -1
		end
	end
end

return Rule